Bitwise Cast

Sometimes you might want to cast a value from one type to another, but instead of calculating some as-close-as-can-be value or other conversion, you just want to have the same bits and bytes interpreted as another type.

To illustrate, here is an example, consider this code:

float a = -10.051;
int b = (int) a;

What do you think the value of b is? -10 probably? Maybe? Here is what the numbers look like in computer memory:

a (-10.051) | 11000001 00100000 11010000 11100101
b (-10)     | 10000000 00000000 00000000 00001010

Quite different now, are they? So the simple C type cast obvoisly does not work in this case the way we want, so what to we do? Pointer-arithmetics! The word every programmer is taught to hate comes in quite handy for once. Remember, we just want to interprete the bits in memory differently, so we have to change the handle to the memory instead of the memory itself:

float a = -10.051;
int b = *((int*) &a);

It a bit ugly, I know, but there is reason behind this mess. We take the address of a &a and cast it to an address of an integer (int*) &a, then we just take what is written at that address (which the compilern now thinks of as an integer) *((int*) &a) and assign that value to b. Now here is what this looks like in memory:

a (-10.051)    | 11000001 00100000 11010000 11100101
b (3240153317) | 11000001 00100000 11010000 11100101

The same data interpreted differently.

2021-05-04 22:07